<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
            <el-form-item label="app名称" prop="place">
                <el-select v-model="queryParams.place" placeholder="app名称">
                    <el-option v-for="(item, index) in plcaelist" :key="index" :label="item.label"
                        :value="item.value"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" :icon="Search" size="small" @click="handleQuery">搜索</el-button>
            </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="info" plain :icon="Upload" size="small" @click="handleImport">上传</el-button>
            </el-col>
        </el-row>

        <el-table v-loading="loading" :data="dataList">
            <el-table-column label="app名称" align="center" key="place" prop="place">
                <template #default="scope">
                    <div v-if="scope.row.place == 1">册子</div>
                    <div v-if="scope.row.place == 2">金塘</div>
                </template>
            </el-table-column>
            <el-table-column label="版本号" align="center" key="appVersion" prop="appVersion" />
            <el-table-column label="是否强制更新" align="center" key="isMandatory" prop="isMandatory">
                <template #default="scope">
                    <div v-if="scope.row.isMandatory">是</div>
                    <div v-if="!scope.row.isMandatory">否</div>
                </template>
            </el-table-column>
            <!-- <el-table-column label="更新内容" align="center" key="versionContent" prop="versionContent" /> -->
            <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button size="small" type="text" :icon="Edit" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button size="small" type="text" :icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
            @pagination="getList" />

        <el-dialog :title="title" v-model="open" width="500px" append-to-body>
            <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
                <el-form-item label="app名称" prop="place">
                    <el-radio-group v-model="form.place">
                        <el-radio :label="1">册子</el-radio>
                        <el-radio :label="2">金塘</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="版本号" prop="appVersion">
                    <el-input v-model="form.appVersion" placeholder="请输入版本号" />
                </el-form-item>
                <el-form-item label="版本更新内容" prop="versionContent">
                    <!-- <el-input v-model="form.versionContent" type="textarea" min="2" placeholder="请输入版本更新内容" /> -->
                    <editor v-model="form.versionContent" :min-height="200" />
                </el-form-item>
                <el-form-item label="是否强制更新" prop="isMandatory">
                    <el-radio-group v-model="form.isMandatory">
                        <el-radio :label="true">是</el-radio>
                        <el-radio :label="false">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="安装包" prop="url">
                    <el-upload ref="faceImgUploadRef" class="avatar-uploader" action="#" :file-list="fileList" accept=".apk"
                        :limit="1" :http-request="handleSuccess" :on-remove="removeList">
                        <el-button size="small" type="primary">点击上传</el-button>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Upload, Edit, Delete } from '@element-plus/icons-vue';
import { appEdit, appAdd, appDetail, appDelete, appUpload, appList, appDeleteMore } from "@/api/apkManage/apkManage";

interface FormData {
    id: string | null;
    isMandatory: boolean;
    appVersion: string | null;
    place: number | null;
    url: string | null;
    versionContent: string | null;
}

interface QueryParams {
    pageNum: number;
    pageSize: number;
    id: string | null;
    appVersion: string | null;
    orderByColumn: string | null;
    isAsc: string | null;
    place: number | null;
    title: string | null;
    url: string | null;
    versionContent: string | null;
}

// 遮罩层
const loading = ref(true);
// 选中数组
const ids = ref<string[]>([]);
// 总条数
const total = ref(0);
// 用户表格数据
const dataList = ref<any[]>([]);
// 弹出层标题
const title = ref("");
// 是否显示弹出层
const open = ref(false);
// 部门名称
const deptName = ref<string | undefined>(undefined);
// 日期范围
const dateRange = ref<string[]>([]);
// 表单参数
const form = reactive<FormData>({
    id: null,//app版本主键id
    isMandatory: false,//是否强制更新
    appVersion: null,//app版本号
    place: null, // 1册子 2金塘
    url: null,// 下载url
    versionContent: null,// app版本更新内容
});
// 表单引用
const formRef = ref<any>(null);
const queryForm = ref<any>(null);
const faceImgUploadRef = ref<any>(null);

// 查询参数
const queryParams = reactive<QueryParams>({
    pageNum: 1,
    pageSize: 10,
    id: null,//app版本主键id
    appVersion: null,//app版本号
    orderByColumn: null,//排序字段,参照返回字段
    isAsc: null,//排序方式排序[asc:正序; desc:倒序]
    place: null, // 1册子 2金塘
    title: null,//版本标题
    url: null,// 下载url
    versionContent: null,// app版本更新内容
});

const rules = {
    appVersion: [
        { required: true, message: '请输入版本号', trigger: 'blur' },
        { pattern: /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/, message: '版本号格式为xxx.xxx.xxx' },
    ],
    place: [
        { required: true, message: '请选择app名称', trigger: 'blur' }
    ],
    versionContent: [
        { required: true, message: '请输入版本更新内容', trigger: 'blur' }
    ],
    url: [
        { required: true, message: '请上传安装包', trigger: 'blur' }
    ],
    isMandatory: [
        { required: true, message: '请选择是否强制更新', trigger: 'blur' }
    ],
};

const fileList = ref<any[]>([]);
const plcaelist = [
    { label: '全部', value: null }, { label: '册子', value: 1 }, { label: '金塘', value: 2 }
];

// 组件挂载完成后执行
onMounted(() => {
    getList();
});

// 删除上传文件
const removeList = (file: any, fileList: any[]) => {
    if (fileList.length === 0) {
        form.url = null;
    }
};

// 上传
const handleSuccess = (res: any) => {
    const reader = new FileReader();
    reader.readAsDataURL(res.file);
    reader.onload = () => {
        let formData = new FormData();
        formData.append("apkfile", res.file);
        appUpload(formData).then(response => {
            form.url = response.data;
            ElMessage.success('上传成功');
        });
    };
};

// 查询用户列表
const getList = () => {
    loading.value = true;
    appList(queryParams).then(response => {
        dataList.value = response.rows;
        total.value = response.total;
        loading.value = false;
    });
};

// 取消按钮
const cancel = () => {
    open.value = false;
    reset();
};

// 表单重置
const reset = () => {
    form.id = null;
    form.isMandatory = false;
    form.appVersion = null;
    form.place = null;
    form.url = null;
    form.versionContent = null;
    
    fileList.value = [];
    nextTick(() => {
        formRef.value?.resetFields();
    });
};

// 搜索按钮操作
const handleQuery = () => {
    queryParams.pageNum = 1;
    getList();
};

// 修改按钮操作
const handleEdit = (row: any) => {
    reset();
    const userId = row.id || ids.value;
    appDetail(userId).then(response => {
        Object.assign(form, response.data);
        
        let list = [];
        let urllist = response.data.url;
        list = urllist.split('/');
        
        let item = {
            name: '',
            url: '',
        };
        
        for (let i = 0; i < list.length; i++) {
            let text = list[i];
            if (text.indexOf('.apk') >= 0) {
                item.name = text.replace('.apk', '');
            }
        }
        
        fileList.value.push(item);
        open.value = true;
        title.value = "详情";
    });
};

// 提交按钮
const submitForm = () => {
    formRef.value?.validate((valid: boolean) => {
        if (valid) {
            if (form.id != null && form.id !== '') {
                appEdit(form).then(response => {
                    ElMessage.success("修改成功");
                    open.value = false;
                    getList();
                });
            } else {
                appAdd(form).then(response => {
                    ElMessage.success("新增成功");
                    open.value = false;
                    getList();
                });
            }
        }
    });
};

// 删除按钮操作
const handleDelete = (row: any) => {
    const userIds = row.id;
    ElMessageBox.confirm('是否确认删除？').then(() => {
        return appDelete(userIds);
    }).then(() => {
        getList();
        ElMessage.success("删除成功");
    }).catch(() => {});
};

// 上传按钮操作
const handleImport = () => {
    reset();
    title.value = "apk上传";
    open.value = true;
};
</script>

<style lang="less">
.el-message-box__wrapper {
    .el-message-box {
        background-color: #fff !important;
        border: 1px solid #EBEEF5 !important;
    }
}
</style>

<style scoped>
.el-button--primary:hover {
    background: rgb(103, 113, 183, .8) !important;
    border: 1px solid rgb(103, 113, 183, .8) !important;
    border-color: 1px solid rgb(103, 113, 183, .8) !important;
}

.el-button--primary:focus {
    background: rgb(103, 113, 183, .8) !important;
    border: 1px solid rgb(103, 113, 183, .8) !important;
    border-color: 1px solid rgb(103, 113, 183, .8) !important;
}

.el-button--primary {
    color: #fff !important;
    background: rgb(103, 113, 183) !important;
    border: 1px solid rgb(103, 113, 183) !important;
    border-color: rgb(103, 113, 183) !important;
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 50px;
    height: 50px;
    line-height: 50px;
    text-align: center;
    border: 1px dashed #DCDFE6;
    background: #F2F6FC;
    border-radius: 4px;
}
</style>